<?php
/**
 * create by sqb 2018/11/26
 */

namespace Admin\Frontend\Controllers;

use Admin\Models\homeset\XhhomeSet;
use Admin\Models\homeset\XhUserSet;
use Helpers\Assets;
use Helpers\Main;
use Helpers\Template;
use Helpers\UserPower;
use Phalcon\Di;

class HomeSetController extends ControllerBase
{
    /**
     * 模块列表页
     */
    public function indexAction()
    {
        if (!UserPower::checkUserPower('HomeSet')) {
            return $this->sendViewError('无操作权限');
        }

        Assets::easyUI('js/home_set/homeSet.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::sweetAlert2();

        $this->view->pick('home_set/index');
        $listButtonArr = $listSearchArr = [];
        $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus'];
        $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        $listSearchArr[] = ['type' => 'select', 'id' => 'select_type', 'label' => ' 默认：',
            'data' => [0 => '全部', 2 => '非默认', 1 => '默认'], 'default' => ''];

        $listSearchArr[] = ['type' => 'select', 'id' => 'model', 'label' => ' 模块：', 'data' => [0 => '--选择--'] + XhhomeSet::getModelName()];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_search', 'label' => ' 名称： '];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
            'icon' => 'fa-search', 'style' => 'margin-left:10px'];
        $this->view->setVars([
            'HomeSetList' => Template::createList('list', 'HomeSet_List', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listSearchArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
        ]);
    }

    /**
     * 获取模块列表接口
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     */
    public function getModelListAction()
    {
        $this->view->disable();

        $sName = $this->request->getPost('name', 'string');
        $model = $this->request->getPost('model', 'string');
        $iIsDefault = $this->request->getPost('isDefault', 'int');

        try {
            $builder = Di::getDefault()->get('modelsManager')->createBuilder()
                ->columns('*')
                ->from(['h' => '\\Admin\\Models\\homeset\\XhhomeSet'])
                ->where('h.bDelete = 0');

            if ($sName) {
                $builder->andWhere('h.sName like :sName:', ['sName' => '%'.$sName.'%']);
            }

            if ($model) {
                $builder->andWhere('h.sModel = :sModel:', ['sModel' => $model]);
            }

            if ($iIsDefault) {
                $builder->andWhere('h.iIsDefault = :iIsDefault:', ['iIsDefault' => $iIsDefault]);
            }

            $data = Main::runBuilderPaginator($builder, true);

            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendDataGridError(500, $e->getMessage());
        }
    }

    /**
     * 删除模块
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     */
    public function delAction()
    {
        if (!UserPower::checkUserPower('HomeSet_Del')) {
            return $this->sendViewError('无操作权限');
        }

        $ids = $this->request->getPost('id', 'string');

        try {
            if (!$ids) {
                throw new \Exception('缺少id');
            }

            $this->db->begin();
            if (!XhhomeSet::deleteRecord('iId', $ids)) {
                throw new \Exception('删除失败');
            }

            //若该模块被删除，则删除所有用户个人配置表中的该model_id
            $userSetObj = XhUserSet::find([
                'conditions' => "bDelete = 0",
            ]);
            if ($userSetObj) {
                foreach ($userSetObj as $item) {
                    $sModelList = json_decode($item->sModelList, true);
                    $newModelList = [];
                    $i = 1;
                    foreach ($sModelList as &$list) {
                        if (! in_array($list['model_id'], $ids)) {
                            $newModelList[$i] = $list;
                            $i++;
                        }
                    }
                    $item->writeAttribute('sModelList', json_encode($newModelList));
                    if (! $item->save()) {
                        throw new \Exception('删除失败');
                    }
                }
            }
            $this->db->commit();

            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 新增模块页面
     */
    public function addAction()
    {
        if (!UserPower::checkUserPower('HomeSet_Store')) {
            return $this->sendViewError('无操作权限');
        }

        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::select2();
        Assets::easyUI('js/home_set/form.js');

        $this->view->pick('home_set/add');

        $iId = $this->request->getQuery('id', 'string');

        if ($iId) {// 编辑
            $info = XhhomeSet::findFirst($iId)->toArray();
        }

        $this->view->setVars(['info' => $info]);
    }

    /**
     * 新增或更新模块接口
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     */
    public function storeAction()
    {
        $this->view->disable();

        $iId = $this->request->getPost('iId', 'string');
        $sName = $this->request->getPost('sName');
        $iIsDefault = $this->request->getPost('iIsDefault');
        $sPowerTag = $this->request->getPost('sPowerTag');
        $sUrl = $this->request->getPost('sUrl');
        $sGetMethod = $this->request->getPost('sGetMethod');
        $sModel = $this->request->getPost('sModel');
        $userId = Main::getLoginUserInfo('userId');

        try {
            $this->db->begin();
            if ($iId) {
                $obj = XhhomeSet::findFirst($iId);
            } else {
                $obj = new XhhomeSet();
                $obj->writeAttribute('tCreateDate', date('Y-m-d H:i:s'));
                $obj->writeAttribute('iCreateUserId', $userId);
                $obj->writeAttribute('iIsDefault', $iIsDefault);
            }

            $obj->writeAttribute('iLastModifyUserId', $userId);
            $obj->writeAttribute('tLastModifyDate', date('Y-m-d H:i:s'));
            $obj->writeAttribute('sName', $sName);
            $obj->writeAttribute('sPowerTag', $sPowerTag);
            $obj->writeAttribute('sUrl', $sUrl);
            $obj->writeAttribute('sGetMethod', $sGetMethod);
            $obj->writeAttribute('sModel', $sModel);

            $res = $obj->save();

            $modelId = $obj->getId();
            if ($iIsDefault == 1) {//默认则插入用户个人配置表
                $userObj = XhUserSet::findFirst([
                    'conditions' => 'bDelete = 0 and iUserId = 0',
                ]);

                if ($userObj) {//更新
                    // [1 => ['model_id' => 10, 'is_show' => 1],...]
                    $sModelList = json_decode($userObj->sModelList, true);

                    $flag = false; //是否存在该modelId
                    foreach ($sModelList as $item) {
                        if ($item['model_id'] == $modelId) {//已存在，则跳过
                            $flag = true;
                            break;
                        }
                    }

                    if (! $flag) {
                        $sModelList[count($sModelList) + 1] = ['model_id' => $modelId, 'is_show' => 1];
                        $userObj->writeAttribute('sModelList', json_encode($sModelList));
                    }
                } else {//添加
                    $userObj = new XhUserSet();
                    $userObj->writeAttribute('sModelList', json_encode([1 => ['model_id' => $modelId, 'is_show' => 1]]));
                    $userObj->writeAttribute('tCreateDate', date('Y-m-d H:i:s'));
                    $userObj->writeAttribute('tLastModifyDate', date('Y-m-d H:i:s'));
                }

                $userObj->writeAttribute('iUserId', 0);
                $userRes = $userObj->save();

                if (!$userRes) {
                    throw new \Exception('保存失败');
                }
            }

            if (!$res) {
                throw new \Exception('保存失败');
            }
            $this->db->commit();

            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 个人配置页面
     */
    public function userSetAction()
    {
        Assets::easyUI('js/home_set/setSave.js');
        $this->view->pick('home_set/userSet');

        $userId = Main::getLoginUserInfo('userId');

        $userModel = [];
        //取出用户设置表中的记录
        $userSet = XhUserSet::findFirst([
            'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
            'bind' => ['iUserId' => $userId]
        ]);
        if (! $userSet) {
            $userSet = XhUserSet::findFirst([
                'conditions' => 'bDelete = 0 and iUserId = 0',
            ]);
        } else {
            $userSetAll = XhUserSet::findFirst([
                'conditions' => 'bDelete = 0 and iUserId = 0',
            ]);
            $sModelListAll = json_decode($userSetAll->sModelList, true);
            $sModelListUser = json_decode($userSet->sModelList, true);

            if (count($sModelListAll) != count($sModelListUser)) {
                foreach ($sModelListAll as $key => $item) {
                    $modelId = $item['model_id'];
                    for ($i=1; $i <= count($sModelListUser); $i++) {
                        if ($sModelListUser[$i]['model_id'] == $modelId) {
                            $sModelListAll[$key]['is_show']=$sModelListUser[$i]['is_show'];
                        }
                    }
                }
                $userSet->sModelList = json_encode($sModelListAll);
            }
        }
        $sModelList = json_decode($userSet->sModelList, true);
        foreach ($sModelList as $item) {
            $modelId = $item['model_id'];
            $modelInfo = XhhomeSet::findFirst([
                'conditions' => 'bDelete = 0 and iId = :iId:',
                'bind' => ['iId' => $modelId]
            ]);
            $power = $modelInfo->sPowerTag;
            if (isset($power) && ! UserPower::checkUserPower($power)) {
                continue;
            }

            $userModel[] = [
                'model_id' => $modelId,
                'sPowerTag' => $power,
                'sUrl' => $modelInfo->sUrl,
                'title' => $modelInfo->sName,
                'sGetMethod' => $modelInfo->sGetMethod,
                'is_show' => $item['is_show']
            ];
        }

        $this->view->setVars(['lists' => $userModel]);
    }

    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     */
    public function userSetSaveAction()
    {
        $data = $this->request->getPost();
        $userId = Main::getLoginUserInfo('userId');

        try {
            $this->db->begin();
            $obj = XhUserSet::findFirst([
                'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
                'bind' => ['iUserId' => $userId]
            ]);

            $flag = true;
            if (! $obj) {
                $obj = XhUserSet::findFirst([
                    'conditions' => 'bDelete = 0 and iUserId = 0',
                ]);
                $flag = false;
            } else {
                $objAll = XhUserSet::findFirst([
                    'conditions' => 'bDelete = 0 and iUserId = 0',
                ]);
                $objAllArray = json_decode($objAll->sModelList, true);
                $objArray = json_decode($obj->sModelList, true);
                if (count($objAllArray) != count($objArray)) {
                    $objAll->iId = $obj->iId;
                    $obj = $objAll;
                }
            }

            $sModelList = json_decode($obj->sModelList, true);

            $newModelList = [];
            $i = 1;
            foreach ($sModelList as $item) {
                $item['is_show'] = $data[$item['model_id']];

                $newModelList[$i] = $item;
                $i ++;
            }

            if (! $flag) {
                $obj = new XhUserSet();
                $obj->writeAttribute('tCreateDate', date('Y-m-d H:i:s'));
            }

            $obj->writeAttribute('sModelList', json_encode($newModelList));
            $obj->writeAttribute('iUserId', $userId);
            $obj->writeAttribute('tLastModifyDate', date('Y-m-d H:i:s'));

            if (! $obj->save()) {
                throw new \Exception('保存失败');
            }

            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendViewError($e->getMessage());
        }
    }
}
